<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="客户类型" prop="userProperty">
        <el-select v-model="queryParams.userProperty" placeholder="请选择">
          <el-option label="请选择" :value="null"></el-option>
          <el-option label="企业" value="3"></el-option>
          <el-option label="个人" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label-width="40" label="ID" prop="userInfoId">
        <el-input
          type="number"
          v-model="queryParams.userInfoId"
          placeholder="请输入ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="principalName">
        <el-input
          v-model.trim="queryParams.principalName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:give:add']"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :height="divHeight"
      v-loading="loading"
      :data="giveList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        fixed="left"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        width="80"
        label="客户ID"
        align="center"
        prop="userInfoId"
      />
      <el-table-column label="客户名称" align="center" prop="principalName"  show-overflow-tooltip/>
      <el-table-column label="联系方式" align="center" prop="principalPhone" show-overflow-tooltip/>
      <el-table-column label="客户类型" align="center" prop="userProperty" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.userProperty == 3">企业</span>
          <span v-if="scope.row.userProperty == 4">个人</span>
        </template>
      </el-table-column>
      <el-table-column label="签约状态" align="center" prop="contractFlag">
        <template slot-scope="scope">
          <span style="color: #00cc00" v-if="scope.row.contractFlag"
            >已签约</span
          >
          <span style="color: #ff0000" v-else>未签约</span>
        </template>
      </el-table-column>
      <el-table-column
        label="累计签收砼量"
        align="center"
        prop="signForCount"
        show-overflow-tooltip
      />
      <el-table-column
        width="200px"
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:give:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleBindUpdate(scope.row)"
            v-hasPermi="['system:give:edit']"
            >账号管理</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:give:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品--服务对话框 -->
    <el-dialog
      destroy-on-close
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        label-position="right"
        :rules="rules"
        label-width="140px"
      >
        <el-card style="padding-top: 20px">
          <el-row>
            <el-col :span="12">
              <el-form-item
                :rules="[{ required: true, message: '请填写客户名称', trigger: 'blur' }]"
                label="客户名称"
                label-width="105px"
                prop="principalName"
              >
                <el-input
                  v-model="form.principalName"
                  placeholder="请输入客户名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :rules="[{ required: true, message: '请填写客户联系方式', trigger: 'blur' }, {
                    validator: validatorPhone,
                    trigger: 'blur',
                  }]"
                label="客户联系方式"
                prop="principalPhone"
              >
                <el-input
                  v-model="form.principalPhone"
                  placeholder="请输入客户联系方式"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :rules="[{ required: true, message: '请选择客户类型', trigger: 'change' }]"
                label="客户类型"
                label-width="105px"
                prop="userProperty"
              >
                <el-radio-group v-model="form.userProperty" @change="userPropertyChange">
                  <el-radio label="3">企业</el-radio>
                  <el-radio label="4">个人</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card style="margin-top: 10px" v-if="form.userProperty == 3">
          <div slot="header" class="clearfix">
            <span>* 客户合同主体公司</span>
            <el-button @click="handleAddCompany" style="float: right; padding: 3px 0" type="text">新增</el-button>
          </div>
          <el-form-item
            v-if="form.userProperty == 3"
            label-width="0"
            :rules="[
              {
                type: 'array',
                required: true,
                message: '请添加客户合同主体公司',
                trigger: 'change',
              },
            ]"
            label=""
            prop="sysClientContractCompanyList"
          >
            <el-table
              :data="form.sysClientContractCompanyList"
              style="width: 100%"
            >
              <el-table-column
                prop="companyName"
                label="企业名称"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="creditCode"
                label="统一社会信用代码"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="companyPhone"
                label="企业联系方式"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="openingBank"
                label="开户银行"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="openingAccountNumber"
                label="开户账号"
                width="180"
              ></el-table-column>
              <el-table-column prop="address" label="企业地址" width="180">
                <template slot-scope="scope">
                  <span
                    >{{ scope.row.provincesName }}{{ scope.row.cityName
                    }}{{ scope.row.districtName }}{{ scope.row.address }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="180"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="deleteList(scope)"
                    v-hasPermi="['system:give:remove']"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-row v-if="form.userProperty == 3">
            <el-col :span="12">
              <el-form-item
                label="企业法人"
                label-width="105px"
                prop="subjectName"
              >
                <el-input
                  v-model="form.subjectName"
                  placeholder="请输入企业法人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="法人身份证"
                prop="idNumber"
              >
                <el-input
                  v-model="form.idNumber"
                  placeholder="请输入法人身份证"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.userProperty == 3">
            <el-col :span="12">
              <el-form-item
                label="董事长/总经理"
                label-width="105px"
                prop="subjectAbbreviation"
              >
                <el-input
                  v-model="form.subjectAbbreviation"
                  placeholder="请输入董事长/总经理"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  :picker-options="{
                    disabledDate: disabledDate,
                  }"
                  style="width: 100%"
                  v-model="form.birthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item
            v-if="form.userProperty == 3"
            label="营业执照"
            label-width="105px"
            prop="idNumberPhoto"
          >
            <FileUpload
              v-model="form.idNumberPhoto"
              :fileType="['png', 'jpg', 'jpeg']"
              :limit="1"
            />
          </el-form-item>
          <el-form-item label-width="105px" label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请填写（限5000字）"
            />
          </el-form-item>
        </el-card>

        <el-card style="margin-top: 10px" v-if="form.userProperty == 4">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <el-row>
            <el-col :span="12">
              <el-form-item label-width="105px" label="居住地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入居住地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  :picker-options="{
                    disabledDate: disabledDate,
                  }"
                  style="width: 100%"
                  v-model="form.birthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
            <el-form-item
              label-width="105px"
              label="身份证照片"
              prop="idNumberPhoto"
            >
              <FileUpload
                v-model="form.idNumberPhoto"
                :fileType="['png', 'jpg', 'jpeg']"
                :limit="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="105px" label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请填写（限5000字）"
              />
            </el-form-item>
          </el-col>
          </el-row>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 账号管理--服务对话框 -->
    <el-dialog
      destroy-on-close
      :title="title"
      :visible.sync="zhOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form-user"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="客户名称" prop="principalName">
          <el-input
            disabled
            v-model="form.principalName"
            placeholder="请输入客户名称"
          />
        </el-form-item>
        <el-form-item
          :rules="[{ required: true, message: '请填写', trigger: 'blur' }]"
          label="账号"
          prop="userName"
        >
          <div style="display: flex; gap: 20px; align-items: center">
            <el-input
              disabled
              v-if="form.userId"
              v-model="form.userName"
              placeholder="请填写"
            />
            <el-input v-else v-model="form.userName" placeholder="请填写" />
            <el-tooltip content="默认密码：123123" placement="top">
              <i style="font-size: 24px" class="el-icon-question"></i>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-switch
            :disabled="!!form.userId"
            :value="form.status === '0'"
            @change="
              (value) => {
                form.status = value ? '0' : '1';
              }
            "
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" v-if="!form.userId" class="dialog-footer">
        <el-button type="primary" @click="addZh">确 定</el-button>
        <el-button @click="zhOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 企业管理--服务对话框 -->
    <el-dialog
      destroy-on-close
      title="新增客户属性-企业"
      :visible.sync="companyOpen"
      width="1000px"
      append-to-body
    >
      <el-form
        ref="form-company"
        label-width="150px"
        :model="companyForm"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              :rules="[{ required: true, message: '请填写企业名称', trigger: 'blur' }]"
              label="企业名称"
              prop="companyName"
            >
              <el-input v-model="companyForm.companyName" placeholder="请填写" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :rules="[{ required: true, message: '请填写统一社会信用代码', trigger: 'blur' }]"
              label="统一社会信用代码"
              prop="creditCode"
            >
              <el-input v-model="companyForm.creditCode" placeholder="请填写" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :rules="[{ required: true, message: '请填写企业联系方式', trigger: 'blur' }, {
                    validator: validatorPhone,
                    trigger: 'blur',
                  }]"
              label="企业联系方式"
              prop="companyPhone"
            >
              <el-input v-model="companyForm.companyPhone" placeholder="请填写" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :rules="[{ required: true, message: '请填写开户银行', trigger: 'blur' }]"
              label="开户银行"
              prop="openingBank"
            >
              <el-input v-model="companyForm.openingBank" placeholder="请填写" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :rules="[{ required: true, message: '请填写开户账号', trigger: 'blur' }]"
              label="开户账号"
              prop="openingAccountNumber"
            >
              <el-input
                v-model="companyForm.openingAccountNumber"
                placeholder="请填写"
              />
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
            <el-form-item
              :rules="[{ required: true, message: '请填写', trigger: 'blur' }]"
              label="企业地址"
            >
              <div style="display: flex; gap: 20px">
                <el-form-item
                  :rules="[{ required: true, message: '请选择省份', trigger: 'change' }]"
                  prop="provinces"
                >
                  <el-select
                    v-model="companyForm.provinces"
                    @change="changePro"
                    placeholder="省份"
                  >
                    <el-option
                      v-for="(value, key) in areaList.province_list"
                      :key="key"
                      :label="value"
                      :value="key"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  :rules="[{ required: true, message: '请选择市', trigger: 'change' }]"
                  prop="city"
                >
                  <el-select
                    v-model="companyForm.city"
                    @change="changeCity"
                    placeholder="市"
                  >
                    <el-option
                      v-for="(value, key) in cityList"
                      :key="key"
                      :label="value"
                      :value="key"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  :rules="[{ required: true, message: '请选择区/县', trigger: 'change' }]"
                  prop="district"
                >
                  <el-select v-model="companyForm.district" placeholder="区/县">
                    <el-option
                      v-for="(value, key) in districtList"
                      :key="key"
                      :label="value"
                      :value="key"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  style="width: 500px"
                  :rules="[{ required: true, message: '请填写详细地址', trigger: 'blur' }]"
                  prop="address"
                >
                  <el-input v-model="companyForm.address" placeholder="详细地址" />
                </el-form-item>
              </div>
            </el-form-item>
          </el-row>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addCompany">确 定</el-button>
        <el-button @click="companyOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  addInfo,
  updateInfo,
  delInfo,
  checkPhone,
  checkUserName
} from "@/api/system/info";
import { addUser, getUser } from "@/api/system/user";
import { areaList } from "@vant/area-data";
import FileUpload from "@/components/FileUpload/index";
import { isArray, isValidPhoneNumber } from "@/utils/validate";
export default {
  name: "Give",
  components: {
    FileUpload,
  },
  data() {
    const validatorPhone = (rule, value, callback) => {
      if (value) {
        if (!isValidPhoneNumber(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      divHeight:300,
      validatorPhone,
      areaList,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品--服务表格数据
      giveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      zhOpen: false,
      companyOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        userType: 5,
        userInfoId: null,
        principalName: null,
        userProperty: null,
      },
      companyForm: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "服务名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.divHeight = window.innerHeight - 300;
    this.getList();
  },
  computed: {
    cityList() {
      const result = {};
      if (this.companyForm.provinces) {
        Object.keys(this.areaList.city_list).forEach((key) => {
          if (
            +this.companyForm.provinces < +key &&
            +this.companyForm.provinces + 10000 > key
          ) {
            result[key] = this.areaList.city_list[key];
          }
        });
      }
      return result;
    },
    districtList() {
      const result = {};
      if (this.companyForm.city) {
        Object.keys(this.areaList.county_list).forEach((key) => {
          if (
            +this.companyForm.city < +key &&
            +this.companyForm.city + 100 > key
          ) {
            result[key] = this.areaList.county_list[key];
          }
        });
      }
      return result;
    },
  },
  methods: {
    userPropertyChange(){

    },
    changePro() {
      this.companyForm.city = null;
      this.companyForm.district = null;
    },
    changeCity() {
      this.companyForm.district = null;
    },
    async addCompany() {
      await this.$refs["form-company"].validate();
      this.companyForm.provincesName =
        this.areaList.province_list[this.companyForm.provinces];
      this.companyForm.cityName = this.cityList[this.companyForm.city];
      this.companyForm.districtName =
        this.districtList[this.companyForm.district];
      this.form.sysClientContractCompanyList.push({
        ...this.companyForm,
      });
      this.$refs.form.validateField('sysClientContractCompanyList')
      this.companyOpen = false;
    },
    /** 查询产品--服务列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        this.giveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    disabledDate(date) {
      const dyear = date.getFullYear().toString();
      const dmonth = date.getMonth().toString().padStart(2, 0);
      const dda = date.getDate().toString().padStart(2, 0);

      const now = new Date();
      const year = now.getFullYear().toString();
      const month = now.getMonth().toString().padStart(2, 0);
      const da = now.getDate().toString().padStart(2, 0);
      const d = dyear + "" + dmonth + dda;
      const cur = year + "" + month + da;

      return +d >= +cur;
    },
    handleAddCompany() {
      this.companyOpen = true;
      this.companyForm = {
        // id: Date.now() + "fsafwsa" + Math.random(),
        companyName: '', // 公司名称
        creditCode: '', //社会信用代码
        companyPhone: '', // 手机号
        openingBank: '', // 开户行
        openingAccountNumber: '', // 开户账号
        provinces: '', //省编码
        provincesName: '', //省名称
        city: '', // 市编码
        cityName: '', // 市名称
        district: '', // 区县 编码
        districtName: '', // 区县名称
        address: '', // 地址
      };
    },
    // 表单重置
    reset() {
      this.form = {
        id: '',
        sysClientContractCompanyList: [],
        userType: 5,
        userProperty: '',
        principalName: '',
        principalPhone: '',
        idNumber: '',
        subjectAbbreviation: '',
        address: '',
        idNumberPhoto: '',
        birthday: '',
        subjectName: '',
        remark: '',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userInfoId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增客户";
    },
    deleteList(e) {
      this.form.sysClientContractCompanyList.splice(e.$index, 1);
    },
    /** 账号管理按钮操作 */
    async handleBindUpdate(row) {
      this.reset();
      const id = row.userInfoId || this.ids;
      const formData = {
        userName: "",
        status: "1",
      };
      if (row.userId) {
        const res = await getUser(row.userId);
        formData.userName = res.data.userName;
        formData.status = res.data.status;
      }
      getInfo(id).then((response) => {
        this.form = {
          ...response.data,
          ...formData,
        };
        this.zhOpen = true;
        this.title = "客户账号管理";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.userInfoId || this.ids;
      getInfo(id).then((response) => {
        this.form = response.data;
        if (this.form.type == "0") {
          this.form = {
            ...this.form,
            radio: "0",
            price1: this.form.price,
            price2: null,
            type: null,
          };
        } else {
          this.form = {
            ...this.form,
            radio: "1",
            price1: null,
            price2: this.form.price,
          };
        }
        this.open = true;
        this.title = "修改客户";
      });
    },
    async addZh() {
      await this.$refs["form-user"].validate();
      await addUser({
        userName: this.form.userName,
        nickName: this.form.principalName,
        userInfoId: this.form.userInfoId,
        userType: 5,
        status: this.form.status,
      });
      this.$modal.msgSuccess("绑定成功");
      this.zhOpen = false;
      this.getList();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async(valid) => {
        if (valid) {
      const resArr =  await Promise.all([
            checkPhone({
              principalPhone:this.form.principalPhone,
              userType:this.form.userType,
            }),
            checkUserName({
              userName:this.form.principalName,
              userType:this.form.userType,
            })])
            if (resArr.every((item) => item.data)){
              return this.$modal.msgError('存在重复用户或联系方式')
            }
          if (this.form.userInfoId != null) {
            updateInfo(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.userInfoId || this.ids;
      const message = Array.isArray(ids)
        ? '是否确认删除客户id为"' + ids + '"的数据项？'
        : "是否确认删除此客户吗";

      this.$modal
        .confirm(message)
        .then(function () {
          return delInfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/give/export",
        {
          ...this.queryParams,
        },
        `give_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container{
  overflow: hidden;
}
  ::v-deep .el-dialog__body {
    max-height: 700px;
    overflow: auto;
  }
</style>